package com.are.inventario;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class SendInfoUpdateTrafo {
	private URL Url;
	private byte bytes[];
	private String filename;
	
	
	public SendInfoUpdateTrafo(String url, byte[] bytes, String filename) {
		super();
		try {
			this.Url = new URL(url);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.bytes = bytes;
		this.filename = filename;
	}
	
	public String Send(String codigo, String tipo, String imei) {
		String result = "";
		HttpURLConnection urlConnection = null;

		try {
			urlConnection = (HttpURLConnection) Url.openConnection();
			urlConnection.setDoOutput(true);
			
			DataOutputStream out = new DataOutputStream(
					urlConnection.getOutputStream());
			
			out.writeUTF(codigo);
			out.writeUTF(tipo);
			out.writeUTF(this.filename);
			out.writeUTF(imei);
			
			String stringImage = Base64.encode(this.bytes);
			out.write(stringImage.getBytes());
			
			out.flush();

			InputStream in = new BufferedInputStream(
					urlConnection.getInputStream());

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					in, "utf-8"));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			in.close();
			result = sb.toString();
			System.out.println(result);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		} finally {
			if (urlConnection != null) {
				urlConnection.disconnect();
			}
		}
		return result;
	}

}
